<template>
  <v-layout type="main">
    <div class="layout-top">
      <div class="rollback" @click="$router.push('/gameDistributedTraining')">
        <img src="~@/assets/img/prev.png" alt />
        <span>返回</span>
      </div>

      <div class="code-description">
        <div class="dea_top">
          <div>
            <el-image
              class="nav_box"
              :src="
                detailData.avatar
                  ? detailData.avatar
                  : require('@/assets/img/drone3.jpg')
              "
              fit="fit"
            ></el-image>
          </div>

          <div class="header_box">
            <div class="code-desc-header">
              <div class="title">
                <div class="title-header">
                  <span>{{ detailData.name }}</span>
                </div>

                <div class="code-tags">
                  <div class="user-tag tag">
                    <img src="~@/assets/img/user.png" alt />
                    {{
                    detailData.create_user &&
                    (detailData.create_user.nick_name ||
                    detailData.create_user.username)
                    }}
                  </div>

                  <div
                    :class="[
                      'status-tag tag',
                      {
                        danger: detailData.status === 'terminated',
                        warning:
                          detailData.status != 'terminated' &&
                          detailData.status != 'running',
                        success: detailData.status === 'running',
                      },
                    ]"
                  >{{ statusMap[detailData.status] }}</div>

                  <div class="time-tag tag">
                    <span>创建时间：</span>
                    {{ detailData.create_time }}
                  </div>
                </div>

                <div class="staet_box">
                  <plug-state :statusStr="detailData.status" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="btns-container">
        <div class="alick-handle-btns">
          <el-button
            class="handle-btn"
            type="success"
            size="medium"
            @click="goDashboard"
            v-show="
              this.detailData.tcp_port_list &&
              Array.isArray(this.detailData.tcp_port_list) &&
              this.detailData.tcp_port_list.length > 0
            "
          >打开 dashboard</el-button>
          <el-button
            class="handle-btn"
            type="success"
            size="medium"
            @click="start"
            v-show="detailData.status == 'terminated'"
          >启动</el-button>

          <el-button
            class="handle-btn"
            type="primary"
            size="medium"
            @click="goToTensorboard"
            v-show="
              detailData.status == 'running' && detailData.tensorboard == true
            "
          >打开tensorboard</el-button>

          <!--					<el-button-->
          <!--						class="handle-btn"-->
          <!--						type="primary"-->
          <!--						size="medium"-->
          <!--						@click="goToLink(detailData.simulation_home_url)"-->
          <!--						v-show="detailData.status != 'terminated' && !detailData.simulation_home_url_list"-->
          <!--					>-->
          <!--						打开仿真前端-->
          <!--					</el-button>-->

          <!--					<el-dropdown v-if="detailData.status == 'running' && detailData.simulation_home_url_list">-->
          <el-dropdown v-show="detailData.status == 'running'" trigger="click">
            <el-button type="primary" style="margin-right: 10px" @click="getEndpoint">
              打开仿真前端
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>

            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="(item, index) in endpointList" :key="index">
                <span @click="goToLink(item)">仿真前端{{ index + 1 }}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-button
            class="handle-btn"
            type="danger"
            size="medium"
            @click="stop"
            v-show="detailData.status != 'terminated'"
          >停止</el-button>

          <el-popover
            placement="bottom-end"
            width="80"
            trigger="hover"
            v-show="detailData.status == 'running'"
          >
            <div class="alick-popover-handle-btns">
              <a class="handle-btn" href="javascript:;" @click="entry">进入VSCode</a>
              <a class="handle-btn" href="javascript:;" @click="entryBt">强化学习行为树</a>
            </div>
            <el-button class="handle-btn" type="warning" size="medium" slot="reference">模型开发</el-button>
          </el-popover>

          <el-popover placement="bottom-end" width="80" trigger="hover">
            <div class="alick-popover-handle-btns">
              <a class="handle-btn" href="javascript:;" @click="exportModel">导出模型</a>
              <a class="handle-btn" href="javascript:;" @click="exportTask">训练任务</a>
              <a class="handle-btn" href="javascript:;" @click="exportAlgorithm">发布到公开算法</a>
            </div>
            <el-button class="handle-btn" type="warning" size="medium" slot="reference">更多</el-button>
          </el-popover>
        </div>
      </div>
    </div>

    <!-- <el-radio-group v-model="nowRouter" size="medium" @change="skip" class="nav-alike" v-show="!$route.meta.hideDetails">
      <el-radio-button :label="e.name" v-for="(e, i) in thisRouter" :key="i">
        <span class="nav-alike-item">{{ e.meta.title }}</span>
      </el-radio-button>
    </el-radio-group>-->

    <div class="tabs-left">
      <el-tabs v-model="nowRouter" @tab-click="skip" v-show="!$route.meta.hideDetails">
        <el-tab-pane :label="e.meta.title" :name="e.name" v-for="(e, i) in thisRouter" :key="i" />
      </el-tabs>
    </div>

    <div
      :class="[
        'layout-content',
        { 'layout-content-nodetail': $route.meta.hideDetails },
      ]"
    >
      <router-view
        class="content-detail"
        :detailData.sync="detailData"
        @infoData="infoData"
        v-if="detailData"
      />
    </div>

    <div v-if="showExportModelDialog">
      <plug-export-model
        :show_file.sync="showExportModelDialog"
        @infoShow="infoShowExport"
        :model_id="model_id"
        :biz_id="detailData.id"
        :business_type="3"
      />
    </div>

    <!-- <el-dialog :visible.sync="showUpdateBaseDialog" title="模型开发基本信息" width="840px">
      <el-form class="form myself-form" ref="form" :rules="baseSubmitRules" :model="taskForm" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input type="text" v-model="taskForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" :rows="3" v-model="taskForm.desc" />
        </el-form-item>
        <el-form-item label="配图">
          <media-uploader accept=".jpg,.jpeg,.png,.JPG,.JPEG" :src="taskForm.avatar" @avatarPath="avatarPath" />
        </el-form-item>
        <el-form-item label="" prop="tensorboard">
          <el-checkbox v-model="taskForm.tensorboard">tensorboard</el-checkbox>
        </el-form-item>
        <el-form-item label=" ">
          <el-button class="none-type" type="primary" @click="commitBase">确定</el-button>
          <el-button class="none-type" @click="cancelBase">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>-->
  </v-layout>
</template>

<script>
import plugState from "@/components/module/plug-state";
import { getMarketAlgorithmBySource } from "@/api/marketAlgorithm";
import { getGameTaskBySource } from "@/api/gameTask";
import {
  getGameExperimentDetail,
  putGameExperiment,
  startGameExperiment,
  stopGameExperiment
} from "@/api/gameExperiment";
import { domain } from "@/config";
import { getModelBySource } from "@/api/model";
import plugExportModel from "@/components/module/plug-export-model";

export default {
  data() {
    return {
      app_user: process.env.VUE_APP_USER,
      nowRouter: this.$route.name,
      thisRouter: [],
      detailData: null,
      taskForm: {},
      model_id: null,
      modelForm: { visibility: 0 },
      marketForm: {},
      taskSubmitRules: {
        task_id: [{ required: true, message: "该项为必填项" }]
      },
      modelSubmitRules: {
        model_id: [{ required: true, message: "该项为必填项" }]
      },
      marketSubmitRules: {
        model_id: [{ required: true, message: "该项为必填项" }]
      },
      showTaskDialog: false,
      showMarketDialog: false,
      // showUpdateBaseDialog: false,
      showExportModelDialog: false,
      taskOptions: [],
      modelOptions: [],
      marketAlgorithmOptions: [],
      task: null,
      model: null,
      algorithm: null,
      podUrl: null,
      simulationHomeUrl: null,
      hasMaster: false,
      endpointList: []
    };
  },
  components: {
    plugExportModel,
    plugState
  },
  methods: {
    getEndpoint() {
      if (
        "simulation_home_url_list" in this.detailData &&
        this.detailData.simulation_home_url_list.length > 0
      ) {
        if (this.detailData.simulation_home_url_list[0].includes("vnc")) {
          this.endpointList = this.detailData.tcp_port_list.map(
            item => item.endpoint + "/vnc.html"
          );
          console.log("this.endpointList", this.endpointList);
        } else if (
          this.detailData.simulation_home_url_list[0].includes("mpts")
        ) {
          this.endpointList = this.detailData.tcp_port_list
            .filter(item => item.containerPort == "8080")
            .map(item => item.endpoint + "/mpts");
          console.log("this.endpointList", this.endpointList);
        }
      }
    },

    goDashboard() {
      if (
        this.detailData.tcp_port_list &&
        Array.isArray(this.detailData.tcp_port_list)
      ) {
        this.hasMaster = this.detailData.tcp_port_list.some(
          port => port.taskName === "master"
        );
        console.log("this.hasMaster", this.hasMaster);
        if (this.hasMaster == true) {
          const masterPort = this.detailData.tcp_port_list[0];
          let path = masterPort.endpoint;
          console.log("masterPort", masterPort.endpoint);
          window.open(`http://${path}`, "_blank");
        }
      } else {
        console.log("tcp_port_list 不存在或不是数组");
      }
    },
    skip() {
      let path = `/gameDistributedTraining/${
        this.thisRouter.filter(e => e.name == this.nowRouter)[0].path
      }`;
      if (path == this.$route.path) return;
      this.$router.push({
        path,
        query: {
          id: this.$route.query.id
        }
      });
    },

    async getDetail() {
      if (!this.$route.query.id) return;
      let res = await getGameExperimentDetail({ id: this.$route.query.id });
      if (res && res.data) {
        this.detailData = res.data;
        this.taskForm = JSON.parse(JSON.stringify(this.detailData));
        if (this.taskForm.simulation_home_url) {
          this.simulationHomeUrl = this.taskForm.simulation_home_url;
        }
      }
      this.genUrl();
    },
    avatarPath(data) {
      this.taskForm.avatar = data;
    },
    updateBase() {
      this.showUpdateBaseDialog = true;
    },

    commitBase() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          let res = await putGameExperiment(this.taskForm);
          if (res && res.data) {
            this.getDetail();
            this.showUpdateBaseDialog = false;
          }
        }
      });
    },
    cancelBase() {
      this.showUpdateBaseDialog = false;
    },
    async exportTask() {
      if (!this.$route.query.id) return;
      let data = {
        source: this.detailData.id
      };
      let task_id = null;
      let res = await getGameTaskBySource(data);
      if (res && res.data) {
        task_id = res.data.id;
      }
      let query = {
        experiment_id: this.detailData.id,
        task_id: task_id
      };
      this.$router.push({
        path: "/gameTask/detail",
        query
      });
    },
    async exportModel() {
      if (!this.$route.query.id) return;
      let data = {
        source: this.detailData.id
      };
      let res = await getModelBySource(data);
      if (res && res.data) {
        this.model_id = res.data.id;
      }
      this.showExportModelDialog = true;
    },

    infoShowExport(data) {
      this.showExportModelDialog = data;
    },

    infoData(data) {
      console.log("infoData", data);
      this.getDetail();
      this.$forceUpdate();
    },
    async exportAlgorithm() {
      if (!this.$route.query.id) return;
      let data = {
        source: this.detailData.id
      };
      let res = await getMarketAlgorithmBySource(data);
      let algorithm_id = null;
      console.log("res", res);
      if (res && res.data) {
        algorithm_id = res.data.id;
      }
      console.log("res2", res);
      let query = {
        experiment_id: this.detailData.id,
        algorithm_id: algorithm_id
      };
      console.log("query", query);
      this.$router.push({
        path: "/algorithm/detail",
        query
      });
    },
    update() {
      let query = {
        id: this.detailData.id
      };
      this.$router.push({
        path: "/gameDistributedTraining/detail",
        query
      });
    },

    start() {
      startGameExperiment({ id: this.detailData.id });
    },
    async stop() {
      await stopGameExperiment({ id: this.detailData.id });
      this.getDetail();
      this.$forceUpdate();
    },
    entry() {
      let path = `${domain.split(":")[1]}:32658` + this.detailData.pod_url;
      // let path = "http://192.168.240.11:32658" + this.detailData.pod_url // 中船
      console.log("path", path);
      window.open(path, "_blank");
    },
    entryBt() {
      const { href } = this.$router.resolve({
        path: "/bTree", //路径
        query: {
          experiment_id: this.detailData.id
        } //传参
      });
      window.open(href);
    },
    goToLink(url) {
      console.log("url", url);
      var urlList = `http://${url}`;
      if (url.includes("vnc")) {
        window.open(urlList, "_blank");
      } else if (url.includes("mpts")) {
        window.open(urlList, "_blank");
      }
    },

    goToTensorboard() {
      let path =
        `${domain.split(":")[1]}:8081` + this.detailData.tensorboard_url;
      console.log("path", path);
      window.open(path, "_blank");
    },
    genUrl() {
      if (
        this.detailData.status != "running" ||
        !this.detailData.tcp_port_list
      ) {
        return null;
      }
      try {
        let tcp_port_list = this.detailData.tcp_port_list;
        let simulationFrontUrl = process.env.VUE_APP_SIMULATION_URL;
        let port4000List = tcp_port_list.filter(
          map => map.containerPort == "4000"
        );
        let nodePort4000 = port4000List[0].nodePort;
        let frontPort = 4001;
        let port4001List = tcp_port_list.filter(
          map => map.containerPort == "4001"
        );
        let frontMap = port4001List[0].nodePort;
        let nodePort4009 = null;
        if (tcp_port_list.length > 9) {
          let port4009List = tcp_port_list.filter(
            map => map.containerPort == "4009"
          );
          if (port4009List.length) {
            nodePort4009 = port4009List[0].nodePort;
          }
        }
        let endpoint = tcp_port_list[0].endpoint.split(":")[0];
        if (nodePort4009 != null) {
          frontPort = 4009;
          frontMap = nodePort4009;
        }
        let url = `${simulationFrontUrl}/#/Menu?IP=${endpoint}&port1=${nodePort4000}&port2=${frontPort}&port3=${frontMap}`;
        this.podUrl = url;
      } catch (error) {
        console.error(error);
      }
    }
  },
  mounted() {
    let temp = this.$router.options.routes.filter(
      e => e.name == "gameDistributedTraining" && e.children
    );
    this.thisRouter = temp[0].children.filter(e => !e.meta.hideDetails);
    this.getDetail();
    this.$EventBus.$on("experiment", e => {
      console.log(e);
      this.getDetail();
    });
  },
  destroyed() {
    this.$EventBus.$off("experiment");
  }
};
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-layout.less";

// .btns-container {
//   // border: 1px solid #f00;

//   .alick-handle-btns {
//     // border: 1px solid #00f;
//   }
// }

.el-dropdown-menu {
  overflow-y: auto; /* 添加垂直滚动条 */
  max-height: 200px; /* 设置最大高度以启用滚动 */
}

/* 自定义滚动条样式 */
.el-dropdown-menu::-webkit-scrollbar {
  width: 10px; /* 设置滚动条宽度 */
}

.el-dropdown-menu::-webkit-scrollbar-track {
  background-color: #f1f1f1; /* 滚动条轨道颜色 */
}

.el-dropdown-menu::-webkit-scrollbar-thumb {
  background-color: #888; /* 滚动条滑块颜色 */
}

.el-dropdown-menu::-webkit-scrollbar-thumb:hover {
  background-color: #555; /* 滚动条滑块hover颜色 */
}
</style>
